import { AudioUrl } from "../Constant/Constant";
import AudioUtil from "../Utils/AudioUtil";

/**
 * 音频管理类
 */
export default class AudioManager {
    private static _audioCacheMap: Map<AudioUrl, cc.AudioClip> = new Map()

    /**
     * 播放背景音乐
     * @param url 
     * @param loop 是否循环播放。可选，默认true 
     */
    public static async playMusic(url: AudioUrl, loop: boolean = true) {
        const audioClip = await this._loadAudio(url)
        let audioId: number = null
        if (audioClip) {
            cc.audioEngine.playMusic(audioClip, loop)
        }
        return audioId
    }

    /**
     * 播放音效
     * @param url 
     * @param loop 是否循环播放。可选，默认false
     */
    public static async playEffect(url: AudioUrl, loop: boolean = false) {
        const audioClip = await AudioUtil.loadAudio(url)
        let audioId: number = null
        if (audioClip) {
            audioId = cc.audioEngine.playEffect(audioClip, loop)
        }
        return audioId
    }

    /**
     * 关闭音乐
     * @param url 
     */
    public static stopMusic() {
        cc.audioEngine.stopMusic()
    }

    /**
     * 加载音频资源（加载过的资源会被缓存）
     * @param url 
     * @returns 
     */
    private static async _loadAudio(url: AudioUrl): Promise<cc.AudioClip | null> {
        let audioClip: cc.AudioClip = this._audioCacheMap.get(url)
        if (!audioClip) {
            audioClip = await AudioUtil.loadAudio(url)
            audioClip && this._audioCacheMap.set(url, audioClip)
        }
        return audioClip
    }
}